const router = require("koa-router")();
let accessToken = "init_s_token"; //短token
let refreshToken = "init_l_token"; //长token
/**
 * 通过长短token实现：短token用来请求应用数据，
 * 长token用于获取新的短token（长短指的是过期时间）
 * 后端存有两个字段，分别保存长短token，并且每一段时间更新他们
短token过期，返回 returncode:104；  accessToken
长token过期，返回 returncode: 108； refreshToken
请求成功返回returncode: 0；
请求头中pass用来接收客户端长token， refreshToken
请求头中authorization用来接收客户端短token accessToken
 * */ 
/* 5s刷新一次短token */
setInterval(() => {
  accessToken = "s_tk" + Math.random();
}, 5000);

/* 一小时刷新一次长token */
setInterval(() => {
  refreshToken = "l_tk" + Math.random();
}, 600000);

/* 登录接口获取长短token */
router.get("/login", async (ctx) => {
  ctx.body = {
    returncode: 0,
    accessToken,
    refreshToken,
  };
});

/* 获取短token */
router.get("/refresh", async (ctx) => {
  //接收的请求头字段都是小写的
  let { pass } = ctx.headers;
  if (pass !== refreshToken) {
    ctx.body = {
      returncode: 108,
      info: "长token过期，重新登录",
    };
  } else {
    ctx.body = {
      returncode: 0,
      accessToken,
    };
  }
});

/* 获取应用数据1 */
router.get("/getData", async (ctx) => {
  let { authorization } = ctx.headers;
  if (authorization !== accessToken) {
    ctx.body = {
      returncode: 104,
      info: "token过期",
    };
  } else {
    ctx.body = {
      code: 200,
      returncode: 0,
      data: { id: Math.random() },
    };
  }
});

/* 获取应用数据2 */
router.get("/getData2", async (ctx) => {
  let { authorization } = ctx.headers;
  if (authorization !== accessToken) {
    ctx.body = {
      returncode: 104,
      info: "token过期",
    };
  } else {
    ctx.body = {
      code: 200,
      returncode: 0,
      data: { id: Math.random() },
    };
  }
});

module.exports = router;